package com.module.overview.ui.cardHistoryDetails.provider

import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.base.app.extras.doOnUiThread
import com.common.base.utils.ViewUtils
import com.module.ble.repo.RespiratoryRateRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/11
 *
 * 描述：体征-呼吸率卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvSignsResRateCardProvider(time:Long,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SIGNS_RES_RATE,
    override val layoutId: Int = R.layout.overview_signs_res_rate_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time

    private var tvAverage: TextView? = null
    private var tvScope: TextView? = null
    private var tvAvg7days: TextView? = null

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        getTheDayResRateData()
        get7DayResRateData()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvAverage = viewHolder.getView(R.id.tvAverage)
        tvScope = viewHolder.getView(R.id.tvScope)
        tvAvg7days = viewHolder.getView(R.id.tvAvg7days)

        super.onViewHolderCreated(viewHolder, viewType)
    }


    /**
     * 获取当天呼吸率
     */
    private fun getTheDayResRateData(){
        if (curTime <=0) return

        //呼吸率
        RespiratoryRateRepo.instance.findAllByDay(curTime)?.let { listIt->

            if (listIt.isNullOrEmpty()) return

            val minTemp = ((listIt.minOfOrNull { it.bpm } ?: 0f).toFloat())
            val maxTemp = ((listIt.maxOfOrNull { it.bpm } ?: 0f).toFloat())
            val theDayAverage = if (listIt.isNotEmpty()) {//当日平均
                listIt.map { it.bpm }.average().toInt()
            } else {
                0f
            }

            doOnUiThread {
                tvAverage?.text = theDayAverage.toString()
                tvScope?.text = "$minTemp~$maxTemp"
            }

        }
    }


    /**
     * 获取7天呼吸率
     */
    private fun get7DayResRateData(){

        //呼吸率
        RespiratoryRateRepo.instance.findLast7DaysFromTimestamp(curTime)?.let { listIt->
            if (listIt.isNullOrEmpty()) return

            val mDayAverage = if (listIt.isNotEmpty()) {//当日平均
                listIt.map { it.bpm }.average().toInt()
            } else {
                0f
            }

            doOnUiThread {
                tvAvg7days?.text = if (mDayAverage.toInt() <=0 ) { ViewUtils.getString(R.string.common_rail_unit) } else { mDayAverage.toInt().toString() }
            }

        }
    }
}